# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Training(models.Model):
    """设备培训模型"""
    _name = 'device.training'
    _description = '设备培训管理'
    _order = 'training_date desc, id desc'
    _rec_name = 'display_name'
    _inherit = ['device.permission.mixin']
    
    # 关联设备
    equipment_id = fields.Many2one('device.equipment', '设备', required=True, ondelete='cascade')
    equipment_name = fields.Char('设备名称', related='equipment_id.name', store=True)
    equipment_code = fields.Char('设备编号', related='equipment_id.code', store=True)
    equipment_category = fields.Char('设备类别', related='equipment_id.category_name', store=True)
    equipment_model = fields.Char('设备型号', related='equipment_id.model', store=True)
    
    # 培训基础信息
    training_date = fields.Date('培训日期', required=True, default=fields.Date.today)
    training_content = fields.Text('培训内容', required=True)
    
    # 培训形式
    training_mode = fields.Selection([
        ('offline', '线下培训'),
        ('online', '线上培训'),
        ('mixed', '混合培训')
    ], string='培训形式', default='offline', required=True)
    
    # 培训师
    trainer_id = fields.Many2one('device.user', '培训师', required=True)
    trainer_name = fields.Char('培训师姓名', related='trainer_id.nick_name', store=True)
    
    # 参与信息
    participant_count = fields.Integer('参与人员数量', required=True, default=1)
    department_id = fields.Many2one('device.department', '参与部门', required=True)
    department_name = fields.Char('部门名称', related='department_id.name', store=True)
    
    # 培训状态
    status = fields.Selection([
        ('planned', '计划中'),
        ('ongoing', '进行中'),
        ('completed', '已完成'),
        ('cancelled', '已取消')
    ], string='培训状态', default='planned', required=True)
    
    # 培训时长
    duration_hours = fields.Float('培训时长（小时）', default=1.0)
    
    # 培训地点
    training_location = fields.Char('培训地点')
    
    # 培训评价
    training_score = fields.Float('培训评分', digits=(3, 1), help='满分10分')
    feedback = fields.Text('培训反馈')
    
    # 文件附件
    attachment_ids = fields.One2many('ir.attachment', 'res_id', 
                                   domain=[('res_model', '=', 'device.training')], 
                                   string='培训附件')
    
    # 附件URL字段 - 存储通过公共上传接口上传的文件URL
    attachment_urls = fields.Text('附件URL列表', help='存储文件URL，多个URL用换行分隔')
    training_material_urls = fields.Text('培训材料URL', help='培训材料文件的URL，多个URL用换行分隔')
    video_urls = fields.Text('培训视频URL', help='培训视频的URL，多个URL用换行分隔')
    certificate_url = fields.Char('培训证书URL', help='培训证书文件的URL')
    photo_urls = fields.Text('培训现场图片URL', help='培训现场图片的URL，多个URL用换行分隔')
    
    # 显示名称
    display_name = fields.Char('显示名称', compute='_compute_display_name', store=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    @api.depends('equipment_id', 'training_date', 'training_content')
    def _compute_display_name(self):
        for record in self:
            if record.equipment_id and record.training_date:
                content_preview = record.training_content[:20] + '...' if len(record.training_content or '') > 20 else record.training_content or ''
                record.display_name = f"{record.equipment_id.name} - {content_preview} ({record.training_date})"
            else:
                record.display_name = "新培训记录"
    
    @api.constrains('participant_count')
    def _check_participant_count(self):
        for record in self:
            if record.participant_count <= 0:
                raise ValidationError('参与人员数量必须大于0。')
    
    @api.constrains('duration_hours')
    def _check_duration_hours(self):
        for record in self:
            if record.duration_hours <= 0:
                raise ValidationError('培训时长必须大于0。')
    
    @api.constrains('training_score')
    def _check_training_score(self):
        for record in self:
            if record.training_score and (record.training_score < 0 or record.training_score > 10):
                raise ValidationError('培训评分必须在0-10分之间。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
    
    def action_start_training(self):
        """开始培训"""
        self.write({'status': 'ongoing'})
    
    def action_complete_training(self):
        """完成培训"""
        self.write({'status': 'completed'})
    
    def action_cancel_training(self):
        """取消培训"""
        self.write({'status': 'cancelled'})
